package com.sixth.docker.service.impl;

import com.alibaba.nacos.shaded.org.checkerframework.checker.units.qual.A;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sixth.core.entity.CareHistory;
import com.sixth.core.vo.R;
import com.sixth.docker.mapper.CareHistoryMapper;
import com.sixth.docker.service.CareHistoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Random;

/**
 * @program: sixth-hospital-parent
 * @description:
 * @author: 赵庆龙
 * @create: 2024-08-19 17:18
 **/
@Service
public class CareHistoryServiceImpl implements CareHistoryService {
    @Autowired
    private CareHistoryMapper careHistoryMapper;
    @Override
    public R<CareHistory> selectById(String registrationId) {
        QueryWrapper<CareHistory> wrapper = new QueryWrapper<>();
        wrapper.eq("reg_id", registrationId);
        CareHistory careHistory = careHistoryMapper.selectOne(wrapper);
        return R.ok(careHistory);

    }

    @Override
    public R<CareHistory> insertOrUpdate(String regId,String patientId) {
        QueryWrapper<CareHistory> wrapper = new QueryWrapper<>();
        wrapper.eq("reg_id", regId);
        CareHistory existingCareHistory = careHistoryMapper.selectOne(wrapper);

        if (existingCareHistory != null) {
            // 如果记录已存在，不做任何修改
            return R.ok(existingCareHistory);
        } else {
            // 如果记录不存在，插入新数据
            System.out.println(patientId);
            CareHistory careHistory = new CareHistory();
            careHistory.setRegId(regId);
            careHistory.setPatientId(patientId);

            // 生成唯一的chId
            String prefix = "CH";
            long timestamp = System.currentTimeMillis();
            Random random = new Random();
            int randomNumber = random.nextInt(1000000);
            String chId = prefix + timestamp + String.format("%06d", randomNumber);

            careHistory.setChId(chId);
            // 其他字段可以保持为空，或者设置为默认值
            careHistoryMapper.insert(careHistory);

            return R.ok(careHistory);
        }
    }

    @Override
    public R<CareHistory> updateById(CareHistory careHistory) {
        QueryWrapper<CareHistory> wrapper = new QueryWrapper<>();
        wrapper.eq("reg_id", careHistory.getRegId());
        //创建时间为现在
        careHistory.setCareTime(new Date());
        if (careHistoryMapper.update(careHistory, wrapper) > 0) {
            return R.ok(careHistory);
        }else {
            return R.error("更新失败");
        }
    }
}